package com.sccl.es.utils;

import com.sccl.es.entity.Content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * @author tangyang
 * @version 1.0
 * @date 2021/4/7 20:40
 */
public class HtmlParseUtil {

    public static void main(String[] args) throws Exception {
/*        //需要联网
        String url = "https://search.jd.com/Search?keyword=java";
        //解析网页(jsoup返回document就是浏览器Document对象)
        Document document = Jsoup.parse(new URL(url),30000);
        //所有的JavaScript方法，都能用这个操作
        Element element = document.getElementById("J_goodsList");
        //获取所有的li元素
        Elements elements = element.getElementsByTag("li");
        //获取元素中的内容，这里el就是每一个li标签
        for (Element el : elements) {
            String img = el.getElementsByTag("img").eq(0).attr("data-lazy-img");
            String price = el.getElementsByClass("p-price").eq(0).text();
            String title = el.getElementsByClass("p-name").eq(0).text();
            System.out.println("-------------------------------------------");
            System.out.println(img);
            System.out.println(price);
            System.out.println(title);
        }
        */
        new HtmlParseUtil().parseJD("java").forEach(System.out::println);
    }

    public List<Content> parseJD(String keyword) throws Exception{
        //需要联网(这里京东地址改了)
        String url = "https://search.jd.com/Search?keyword="+keyword+"&enc=utf-8&wq="+keyword+"&pvid=ea2717cd7d6d45e1acc7cce135ae0718";
        //解析网页(jsoup返回document就是浏览器Document对象)
        Document document = Jsoup.parse(new URL(url),30000);
        //所有的JavaScript方法，都能用这个操作
        Element element = document.getElementById("J_goodsList");
        //获取所有的li元素
        Elements elements = element.getElementsByTag("li");

        List<Content> listContent = new ArrayList<Content>();


        //获取元素中的内容，这里el就是每一个li标签
        for (Element el : elements) {
            String img = el.getElementsByTag("img").eq(0).attr("data-lazy-img");
            String price = el.getElementsByClass("p-price").eq(0).text();
            String title = el.getElementsByClass("p-name").eq(0).text();
/*            System.out.println("-------------------------------------------");
            System.out.println(img);
            System.out.println(price);
            System.out.println(title);*/
            Content content = new Content();
            content.setImg(img);
            content.setPrice(price);
            content.setTitle(title);
            listContent.add(content);
        }
        return listContent;
    }

}
